package bueu.bexl;

import java.util.List;

import static bueu.bexl.utils.TypeUtils.booleanValue;

public class FilterExpr extends ReferenceExpr {

	private final BexlExpr expr;

	public FilterExpr(BexlExpr expr, BexlExpr next) {
		super(next, false);
		
		if (next instanceof FilterExpr) {
			throw new ParseBexlException("No puede haber dos filtros seguidos");
		}

		this.expr = expr;
	}

	public BexlExpr getExpr() {
		return this.expr;
	}

	@Override
	public final String toString() {
		final StringBuilder sb = new StringBuilder("[");
		sb.append(this.expr);
		sb.append(']');
		toStringNext(sb);
		
		return sb.toString();
	}

	protected final void eval(final BexlCtx ctx, final Object current, final boolean set,
			final Object newValue, final List<Object> result) throws BexlException {
		final BexlExpr next = getNext();
		
		if (newValue != null && next == null) {
			throw new BexlException("");
		}
		
		if (booleanValue(this.expr.eval(ctx, current, false, null))) {
			processNext(next, ctx, current, set, newValue, result);
		}
	}
}
